import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/func/permission_util.dart';
import 'package:zhibao_flutter/util/func/tips_util.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:just_throttle_it/just_throttle_it.dart';

/// 防止同时多个事件
/// 关键字：防多次点击、防点击
/// 目前临时使用，只限非组件点击时
///
/// 组件触发全部使用[ClickEvent]
bool isTemporaryTapProcessing = false;

void restoreTemporaryProcess([int milliseconds = 500]) {
  Future.delayed(Duration(milliseconds: milliseconds)).then((value) {
    isTemporaryTapProcessing = false;
  });
}

/// Check Network.
Future netClickEven(VoidCallback callback) async {
  if (await Connectivity().checkConnectivity() == ConnectivityResult.none) {
    LogUtil.d("netClickEven::Fail::ConnectivityResult.none");
    myFailToast(TipsUtil.netError);
  } else {
    LogUtil.d("netClickEven::Success");
    callback();
  }
}

/*
* 防止同时多个事件
*
* 关键字：防多次点击、防点击
* */

/// 通用防重复【防多点】点击组件
class ClickEvent extends StatefulWidget {
  final Widget? child;
  final VoidCallback? onTap;
  final GestureLongPressCallback? onLongPress;

  const ClickEvent({this.onTap, this.onLongPress, this.child});

  @override
  State<ClickEvent> createState() => _ClickEventState();
}

class _ClickEventState extends State<ClickEvent> {
  /// 【2021 12.10】放到全局出现弹出对话框后，对话框内的内容不能点击
  bool isInkWellProcessing = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onLongPress: widget.onLongPress,
      onTap: () {
        /// 防止多个事件一起点
        if (isTemporaryTapProcessing) {
          return;
        }
        isTemporaryTapProcessing = true;
        restoreTemporaryProcess(300);

        Throttle.milliseconds(1000, widget.onTap!);
      },
      child: widget.child ?? Container(),
    );
  }

  @override
  void dispose() {
    Throttle.clear(widget.onTap!);

    super.dispose();
  }
}

class ClickEvenGestureRecognizer extends TapGestureRecognizer {}
